# -*- coding:utf-8 -*-
from flask import request, jsonify, abort
from flask_cors import CORS
from com.zzh.dao_v2.couponUsedDao import CouponUsedDao

from . import app

CORS(app, supports_credentials=True)


@app.route('/insertCouponUsed', methods=['POST'])
def insert_coupon_usedNoToken():
    """
    添加信息
    :return:
    """
    if not request.json:
        abort(400)
    info = {
        'couponId': request.json.get('couponId', 0),
        'userId': request.json.get('userId', 0),
        'timesUsed': request.json.get('timesUsed', 0)
    }

    info = CouponUsedDao().insertCouponUsed(info)
    if info:
        return jsonify({"message": {"code": 1, "status": "success"}})
    else:
        return jsonify({"message": {"code": 0, "status": "error"}})


@app.route('/findCouponUsedById', methods=['POST'])
def find_coupon_used_by_idNoToken():
    """
    根据ID查询
    :return:
    """
    if not request.json:
        abort(400)
    couponId = request.json.get('couponId', '')
    info = CouponUsedDao().findCouponUsedById(couponId)

    if info:
        return jsonify({"info": info, "message": {"code": 1, "status": "success"}})
    else:
        return jsonify({"message": {"code": 0, "status": "error"}})


@app.route('/findCouponUsedByCondition', methods=['POST'])
def find_coupon_used_by_conditionNoToken():
    """
    条件查询
    :return:
    """
    if not request.json:
        abort(400)

    userId = request.json.get('userId', '')
    info = CouponUsedDao().findCouponUsedByCondition(userId=userId)

    if info:
        return jsonify({"info": info, "message": {"code": 1, "status": "success"}})
    else:
        return jsonify({"message": {"code": 0, "status": "error"}})


@app.route('/deleteCouponUsedByIds', methods=['POST'])
def delete_coupon_used_by_idsNoToken():
    """
    根据ID删除，ID以数组形式传递
    :return:
    """
    if not request.json:
        abort(400)
    idArray = request.json.get('idArray', [0])

    info = CouponUsedDao().deleteCouponUsed(idArray)
    if info:
        return jsonify({"message": {"code": 1, "status": "success"}})
    else:
        return jsonify({"message": {"code": 0, "status": "error"}})


@app.route('/updateCouponUsedById', methods=['POST'])
def update_coupon_used_by_idNoToken():
    """
    更新
    :return:
    """
    if not request.json:
        abort(400)
    try:
        id = request.json['id']
    except:
        return jsonify({"message": {"code": 0, "status": "请传入要修改信息的ID"}})
    oldInfo = CouponUsedDao().selectCPused(id)

    info = {
        'id': request.json['id'],
        'couponId': request.json.get('couponId', oldInfo[1]),
        'userId': request.json.get('userId', oldInfo[2]),
        'timesUsed': request.json.get('timesUsed', oldInfo[3])
    }

    info = CouponUsedDao().updateCouponUsed(info)

    if info:
        return jsonify({"info": info, "message": {"code": 1, "status": "success"}})
    else:
        return jsonify({"message": {"code": 0, "status": "error"}})
